package top;

import java.util.ArrayList;
import java.util.List;

/**
 * @author chenyw
 * @date 2022/7/7 22:31
 * @description     螺旋矩阵
 *      使用变量numEle计算总的元素个数，避免最后一步多算
 */
public class Top54spiralOrder {
    public List<Integer> spiralOrder(int[][] matrix) {
        int top = 0;
        int down = matrix.length - 1;
        int left = 0;
        int right = matrix[0].length - 1;
        int numEle = matrix.length * matrix[0].length;
        List<Integer> res = new ArrayList<>();
        while (numEle >= 1) {
            for (int i = left; i <= right && numEle >= 1; i++) {
                res.add(matrix[top][i]);
                numEle--;
            }
            top++;
            for (int i = top; i <= down && numEle >= 1; i++) {
                res.add(matrix[i][right]);
                numEle--;
            }
            right--;
            for (int i = right; i>= left && numEle >= 1; i--) {
                res.add(matrix[down][i]);
                numEle--;
            }
            down--;
            for (int i = down; i >= top && numEle >= 1; i--) {
                res.add(matrix[i][left]);
                numEle--;
            }
            left++;
        }
        return res;
    }
}
